package com.sunrise.configuracoes.repositorio;

import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Repository;

import com.sunrise.configuracoes.repositorio.iface.NaturezaNFDao;
import com.sunrise.generico.acesso.DaoService;
import com.sunrise.generico.entidade.NaturezaNF;
import com.sunrise.generico.visao.Filtro;

@Repository
public class NaturezaNFDaoImpl extends DaoService<NaturezaNF> implements NaturezaNFDao {

	public List<NaturezaNF> listarOrdenado() {
		List<NaturezaNF> list = listar(NaturezaNF.class);
		Collections.sort(list, new Comparator<NaturezaNF>() {

			@Override
			public int compare(NaturezaNF o1, NaturezaNF o2) {
				return o1.getNome().compareTo(o2.getNome());
			}
		});
		return list;
	}

	public List<NaturezaNF> search(NaturezaNF ex) {
		List<NaturezaNF> list =  searchByExample(NaturezaNF.class, ex);
		Collections.sort(list, new Comparator<NaturezaNF>() {

			@Override
			public int compare(NaturezaNF o1, NaturezaNF o2) {
				return o1.getNome().compareTo(o2.getNome());
			}
		});
		return list;
	}

	public NaturezaNF getById(Long id) {
		return getById(id, NaturezaNF.class);
	}
	
	
	@SuppressWarnings("unchecked")
	@Override
	public List<NaturezaNF> listarPorNome(String nome) {
		Criteria crit = getSession().createCriteria(NaturezaNF.class);
		crit.add(Restrictions.ilike("nome", nome, MatchMode.ANYWHERE));
		return crit.list();
	}
	
	
	@SuppressWarnings("unchecked")
	@Override
	public Collection<NaturezaNF> buscarPorFiltros(Filtro naturezaNF) {
		Criteria crit = getSession().createCriteria(NaturezaNF.class);
		if(naturezaNF.getCodigo() != null && !naturezaNF.getCodigo().isEmpty()){
			crit.add(Restrictions.eq("codigo", naturezaNF.getCodigo()));
		}
		
		if (naturezaNF.getNome() != null) {
			crit.add(Restrictions.ilike("nome", naturezaNF.getNome(),
					MatchMode.ANYWHERE));
		}

		if (naturezaNF.getAtivo() != null) {
			crit.add(Restrictions.eq("ativo", naturezaNF.getAtivo().getCodigo()));
		}
		return crit.list();
	}
	
	@Override
	public NaturezaNF buscarPorNome(String nome) {
		Criteria crit = getSession().createCriteria(NaturezaNF.class);
		crit.add(Restrictions.eq("nome", nome).ignoreCase());
		return (NaturezaNF) crit.uniqueResult();
	}

}
